class TripsController < ApplicationController

  require 'uri'
  require 'xmlsimple'
  require 'open-uri'

  FLICKR_API_KEY = '57972cb67a460d2cb3d16c6aac43df9d'
  FLICKR_SEARCH_URL = "http://api.flickr.com/services/rest/?api_key=#{FLICKR_API_KEY}&method=flickr.photos.search"
  
  # GET /trips
  # GET /trips.xml
  def index
    @trips = Trip.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @trips }
    end
  end

  # GET /trips/1
  # GET /trips/1.xml
  def show
	@title = 'Viajes de ' + current_user.name + ' ' + current_user.lastname 
    @trip = Trip.find(params[:id])
	@all_itineraries = Trip.find(params[:id]).itinerary
	@user_invited = Trip.find(params[:id]).user
	@itineraries = @trip.itinerary
	@friend_uninvited = available_friends_for_trip(@trip.id)
	@body_tag = 'onload="initMapTrip()" id="public"'
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @trip }
    end
	rescue ActiveRecord::RecordNotFound
		redirect_to :controller => 'users', :action => "home", :id => current_user.id
  end

  # GET /trips/new
  # GET /trips/new.xml
  def new
    @title = 'Nuevo Viaje'
	@trip = Trip.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @trip }
    end
  end

  # GET /trips/1/edit
  def edit
	@title = 'Editar Viaje'
    @trip = Trip.find(params[:id])
  end

  # POST /trips
  # POST /trips.xml
  def create
    @trip = Trip.new(params[:trip])
    respond_to do |format|
      if @trip.save
	    @trip.user_trip.create(:user_id => current_user.id)
        flash[:notice] = 'El viaje se ha creado con exito.'
        format.html { redirect_to(@trip) }
        format.xml  { render :xml => @trip, :status => :created, :location => @trip }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @trip.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /trips/1
  # PUT /trips/1.xml
  def update
    @trip = Trip.find(params[:id])

    respond_to do |format|
      if @trip.update_attributes(params[:trip])
        flash[:notice] = 'El viaje fue actualizado con exito'
        format.html { redirect_to(@trip) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @trip.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /trips/1
  # DELETE /trips/1.xml
  def destroy
    @trip = Trip.find(params[:id])
    @trip.destroy

    respond_to do |format|
      format.html { redirect_to :controller => 'users', :action => 'home', :id => current_user.id }
      format.xml  { head :ok }
    end
  end
  
  def close_trip
	@trip = Trip.find(params[:id])
	respond_to do |format|
		if @trip.update_attributes(:tri_status => 0)
			flash[:notice] = 'El viaje ha sido cerrado con exito'
			format.html { redirect_to(@trip) }
			format.xml  { head :ok }
		else
			flash[:notice] = 'El viaje no se pudo cerrar'
			format.html { redirect_to(@trip)}
			format.xml  { head :ok }
		end
	end
  end
  
	def flickr
		@title = 'Nuevo Itinerario'
		@trip = Trip.find(params[:id])
	end
	
	def find_photos
		@title = 'Fotos del Itinerario'
		@trip = Trip.find(params[:trip_id])
		@iti_location = params[:iti_location] 
		tags = @trip.tri_country + ' ' + @trip.tri_city + ' ' + @iti_location
		@latitude = params[:latitude]
		@longitude = params[:longitude]
		# creamos la lista de parametros para agregar al URL
		hash = {:text => tags, :per_page => 27, :tag_mode => 'all'}

		# creamos un query string uniedo clave y valor del hash anterior y los separamos por &
		parameters = URI.escape(hash.to_a.collect {|pair| pair.join('=')}.join('&'))

		results = ''
		@pics = []
		  
		open(FLICKR_SEARCH_URL + '&' + parameters) {
		  |s| results = XmlSimple::xml_in(s.read, 'force_array' => false)
		}

		# EL XML con el resultado contiene un tag llamado "photos" y dentro
		# del existen muchos tags de nombre "photo" para cada uno de ellos
		# obtenemos URL y titulo de la foto
		
		results['photos']['photo'].each{	  
			|p|	@pics << ["http://farm#{p['farm']}.static.flickr.com/#{p['server']}/#{p['id']}_#{p['secret']}.jpg"]
		}
		flash[:notice] = ''
		rescue
			flash[:notice] = 'No se consiguieron fotos para el destino. Intenta de nuevo!'
			render :template => 'trips/flickr'
			#redirect_to :controller => 'trips', :action => 'flickr'
		
    end
	
	def available_friends_for_trip(trip)
		friends = Friendship.find(:all,:conditions => {:user_a_id => current_user.id, :status => 1})
		friends_invited = UserTrip.find(:all, :conditions => {:trip_id => trip})
		friends_uninvited = []
		
		friends.each do |friend|
			is_invited = false		
			friends_invited.each do |friend_invited|
				if friend.user_b_id == friend_invited.user_id
					is_invited = true
				end
			end
			if !is_invited
				user = User.find(friend.user_b_id)
				friends_uninvited << user
			end 
		end		
		friends_uninvited
	end
 end

